package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("shopping")
public class CartsController {

    @Reference(timeout = 2000, retries = 0, check = false)
    ICartService cartService;

    @PostMapping("carts")
    public ResponseData addCart(@RequestBody AddCartRequest addCartRequest) {
        addCartRequest.requestCheck();
        AddCartResponse addCartResponse = cartService.addToCart(addCartRequest);
        if (addCartResponse.getCode().equals(ShoppingRetCode.SUCCESS.getCode())) {
            return new ResponseUtil<>().setData("成功");
        }
        return new ResponseUtil<>().setErrorMsg(addCartResponse.getMsg());
    }


    @GetMapping("carts")
    public ResponseData cartList(HttpServletRequest request){
        String userInfo = (String) request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        long uid = Long.parseLong(userInfo);

        CartListByIdRequest cartListRequest = new CartListByIdRequest();
        cartListRequest.setUserId(uid);
        CartListByIdResponse response = cartService.getCartListById(cartListRequest);

        if (response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setData(response.getCartProductDtos());
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @PutMapping("carts")
    public ResponseData cartUpdate(@RequestBody UpdateCartNumRequest request) {
        request.requestCheck();//测试传入的参数是否合法 不合法抛出异常
        //todo
        UpdateCartNumResponse response = cartService.updateCartNum(request);
        if (!response.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
            return new ResponseUtil().setErrorMsg(response.getMsg());
        }
        return new ResponseUtil<>().setData(response.getMsg());

    }
}
